package com.dstz.bus.script;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.dstz.base.api.exception.BusinessMessage;
import com.dstz.base.core.util.StringUtil;
import com.dstz.bus.api.model.IBusinessData;
import com.dstz.bus.model.BusTableRel;
import com.dstz.bus.model.BusinessColumn;
import com.dstz.bus.model.BusinessData;
import com.dstz.bus.service.BusinessDataService;
import com.dstz.sys.api.groovy.IScript;
import com.dstz.sys.api.service.ISysTreeNodeService;

/**
 * 业务对象常用脚本
 *
 */
@Component
public class BusDataScript implements IScript{
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	BusinessDataService businessDataService;
	
	/**
	 * 业务对象转 JSON
	 * @param busData
	 * @return
	 */
	public JSONObject busData2Json(BusinessData busData) {
		JSONObject object =	 businessDataService.assemblyFormDefData(busData);
		return object;
	}
	
	/**
	 * JSON 转 业务对象
	 * @param busData
	 * @param boKey
	 * @return
	 */
	public IBusinessData json2BusData(JSONObject busData,String boKey) {
		IBusinessData businessData = businessDataService.parseBusinessData(busData, boKey);
		return businessData;
	}

	
	/**
	 * 判断业务对象是否已经存在
	 * @param businessData 业务对象 
	 * @param columnName 字段名
	 * @param 提示消息
	 * @return
	 */
	public void checkBusDataIsExist(BusinessData busData,String columnName,String msg){
		
		BusTableRel tableRel = busData.getBusTableRel();
		String sql="";
		Object[] aryObj=null;
		Object columnValue = busData.get(columnName);
		 
		BusinessColumn column =tableRel.getTable().getColumnByKey(columnName);
		
		//添加
		if(busData.getPk() == null){
			aryObj=new Object[1];
			aryObj[0]= columnValue;
			sql = "select count(*) from " + tableRel.getTableKey() +" where " +  column.getKey() +"=?" ;
		}
		//更新数据
		else{
			aryObj=new Object[2];
			aryObj[0] = columnValue;
			aryObj[1] = busData.getPk();
			sql="select  count(*) from " + tableRel.getTableKey() +" where " + column.getKey() +"=? and " + tableRel.getTable().getPkKey() +"!=?" ;
		}
		
		Integer rtn = jdbcTemplate.queryForObject(sql, aryObj,Integer.class);
		if(rtn>0){
			if(StringUtil.isNotEmpty(msg)){
				 msg = String.format("字段%s数据[%s]已经存在！", column.getComment(),columnValue) ;
			}
			throw new BusinessMessage(msg);
		}
	}
	

}
